package maldade.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import maldade.action.util.RequestTool;
import maldade.configuration.EMessages;
import maldade.persistence.model.Example;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * Example action.
 * 
 * @author rnojiri
 */
public class ExampleAction extends AbstractMappingDispatchAction
{
	private static final String PARAM_EXAMPLE_NAME = "name";
	private static final String PARAM_EXAMPLE = "example";
	private static final String ATTRIB_EXAMPLE_LIST = "exampleList";
	
	/**
	 * Saves a new example.
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward saveExample(ActionMapping mapping, ActionForm form,
			   HttpServletRequest request, HttpServletResponse response)
	{
		String name = RequestTool.getString(PARAM_EXAMPLE_NAME, true, request);
		String example = RequestTool.getString(PARAM_EXAMPLE, true, request);
		
		boolean hasError = false;
		
		if(name == null)
		{
			messageLoader.addMessage(EMessages.example_name_required, request);
			
			hasError = true;
		}
		
		if(example == null)
		{
			messageLoader.addMessage(EMessages.example_required, request);
			
			hasError = true;
		}
		
		if(hasError)
		{
			return mapping.findForward(FAIL_FORWARD);
		}
		
		Example newExample = new Example();
		
		newExample.setName(name);
		newExample.setExample(example);
		
		exampleService.saveExample(newExample);
		
		return mapping.findForward(SUCCESS_FORWARD);
	}
	
	/**
	 * Lists all examples.
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward listExamples(ActionMapping mapping, ActionForm form,
			   HttpServletRequest request, HttpServletResponse response)
	{
		List<Example> exampleList = exampleService.getAllExamples();
		
		request.setAttribute(ATTRIB_EXAMPLE_LIST, exampleList);
		
		return mapping.findForward(SUCCESS_FORWARD);
	}
	
	/**
	 * Finds examples by name.
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward findExamples(ActionMapping mapping, ActionForm form,
			   HttpServletRequest request, HttpServletResponse response)
	{
		String name = RequestTool.getString(PARAM_EXAMPLE_NAME, true, request);

		if(name == null)
		{
			messageLoader.addMessage(EMessages.example_name_required, request);
			
			return mapping.findForward(FAIL_FORWARD);
		}
		
		List<Example> exampleList = exampleService.getExamplesByName(name);
		
		request.setAttribute(ATTRIB_EXAMPLE_LIST, exampleList);

		return mapping.findForward(SUCCESS_FORWARD);
	}
}
